package com.idbk.chargestation.activity.pile;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.adapter.PointListAdapter;
import com.idbk.chargestation.adapter.TJDropdownAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.bean.JsonPointsList;
import com.idbk.chargestation.bean.JsonPointsOverview;
import com.idbk.chargestation.bll.PointFilter;
import com.idbk.chargestation.bll.PointFilter.PointFilterModel;
import com.idbk.chargestation.fragment.FragmentMap;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.util.MapUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 充电点列表
 *
 * @author lupc, zhx
 */
public class ActivityPointList extends AppCompatActivity implements OnClickListener {

    public final static String TAG = ActivityPointList.class.getSimpleName();

    public final static String KEY_MODEL = "key_model";
    public final static String KEY_KEYWORD = "key_keyword";

    public final static int MODEL_NORMAL = 0;
    public final static int MODEL_KEYWORD = 1;
    public final static int MODEL_NEARBY = 2;

    private Context mContext;

    private TextView mTextSearch;

    private List<JsonPointsOverview> mData;
    private ListView mListView;
    private PointListAdapter mAdapter;

    private ProgressDialog mDialog;

    private LinearLayout mLayoutEmpty, mLayoutError;

    private View mViewPopParent;

    private PopupWindow mPopWindow;

    private int mIndexArea = 0, mIndexOrder = 0;

    private final static String[] AREA_INFO_ARRAY = new String[]{
            "全部",
            "附近<font color='#999999'>（1公里以内）</font>",
            "较近<font color='#999999'>（10公里以内）</font>",
            "较远<font color='#999999'>（30公里以内）</font>",
    };
    private final static int[] AREA_VALUE_ARRAY = new int[]{
            0, 1000, 10000, 30000
    };

    private final static String[] SORT_INFO_ARRAY = new String[]{
            "距离远近（默认排序）",
            "空闲优先",
            "好评优先",
    };

    /**
     * 过滤的数据模型
     */
    private PointFilter.PointFilterModel mPointFilterModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_point_list);

        setupView();

        setupData();
    }

    @SuppressWarnings("ConstantConditions")
    public void setupView() {
        mContext = ActivityPointList.this;

        mTextSearch = (TextView) findViewById(R.id.textview_search);

        mLayoutEmpty = (LinearLayout) findViewById(R.id.tj_empty_view);
        mLayoutError = (LinearLayout) findViewById(R.id.tj_error_view);
        if (mTextSearch != null && mLayoutError != null) {
            mTextSearch.setOnClickListener(this);
            mLayoutError.setOnClickListener(this);
        }

        findViewById(R.id.imageview_back).setOnClickListener(this);

        //3个筛选
        findViewById(R.id.layout_area).setOnClickListener(this);
        findViewById(R.id.layout_order).setOnClickListener(this);
        findViewById(R.id.layout_other).setOnClickListener(this);

        mViewPopParent = findViewById(R.id.layout_pop_parent);

        mListView = (ListView) findViewById(R.id.listview);
        setCurrentLocation();
        mData = new ArrayList<JsonPointsOverview>();
        mAdapter = new PointListAdapter(mContext, mData);//初始化adapter对象，对象类型为自定义SearchListAdapter，同时传入两个参数
        mListView.setAdapter(mAdapter);//为ListView组件添加适配器
    }

    private void setCurrentLocation() {
        TextView mTextLocation = (TextView) LayoutInflater.from(this)
                .inflate(R.layout.activity_pointlist_textview_location, mListView, false);

        mTextLocation.setText(FragmentMap.locationAddress);
        mListView.addHeaderView(mTextLocation);
    }

    private void setupData() {
        mPointFilterModel = new PointFilterModel();

        processIntent();
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonPointsList result = GsonUtils.toBean(JsonPointsList.class, response);
            if (result == null) { //返回状态为空！
                Toast.makeText(mContext, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();

            } else if (result.status == GlobalResult.OK.getStatus()) {
                mData.clear();
                if (result.points.size() == 0) {
                    mLayoutError.setVisibility(View.GONE);
                    mLayoutEmpty.setVisibility(View.VISIBLE);
                    mListView.setVisibility(View.GONE);

                } else {
                    mLayoutError.setVisibility(View.GONE);
                    mLayoutEmpty.setVisibility(View.GONE);
                    mListView.setVisibility(View.VISIBLE);
                }
                mData.addAll(result.points);

                doPointFilter();

                mAdapter.notifyDataSetChanged();
            } else {
                //标准异常返回
                Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            mLayoutError.setVisibility(View.VISIBLE);
            mLayoutEmpty.setVisibility(View.GONE);
            mListView.setVisibility(View.GONE);
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            mDialog.dismiss();
        }

    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);

        processIntent();
    }

    private void processIntent() {
        //显示加载框
        mDialog = ProgressDialog.show(mContext, null, "加载中...", true, false, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mDialog != null) {
                    mDialog.dismiss();
                }
                finish();
            }
        });
        int model = getIntent().getIntExtra(KEY_MODEL, MODEL_NORMAL);
        if (model == MODEL_NORMAL) {
            ChargeStationAPI.getPointsOverview(mResponse);
        } else if (model == MODEL_KEYWORD) {
            String keyword = getIntent().getStringExtra(KEY_KEYWORD);
            if (keyword != null && !"".equals(keyword)) {
                //关键字搜索
                mTextSearch.setText(keyword);
                //组合关键字，加上当前城市限定
                keyword = AppContext.getInstance().getCurrentCityName() + " " + keyword;
                ChargeStationAPI.keywordSearch(keyword, mResponse);
            }
        } else if (model == MODEL_NEARBY) {
            mIndexArea = 1;
            ChargeStationAPI.getPointsOverview(mResponse);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tj_error_view:
                setupData();
                break;
            case R.id.imageview_back:
                finish();
                break;
            case R.id.layout_area:
                showPopupWindow1();
                break;
            case R.id.layout_order:
                showPopupWindow2();
                break;
            case R.id.layout_other:
                showPopupWindow3();
                break;
            case R.id.textview_search:
                Intent intent = new Intent(this, ActivityKeyWordSearch.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void showPopupWindow1() {
        View view = LayoutInflater.from(this).inflate(R.layout.listview_for_tj_dropdown, new LinearLayout(this), false);
        ListView lv = (ListView) view.findViewById(R.id.listview);

        final TJDropdownAdapter adapter = new TJDropdownAdapter(this, AREA_INFO_ARRAY);
        adapter.setSelectedItemIndex(mIndexArea);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                adapter.setSelectedItemIndex(position);
                adapter.notifyDataSetChanged();
                mIndexArea = position;
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                //执行过滤
                doPointFilter();
            }
        });

        showViewWithPopWindow(view, 0);
    }

    private void showPopupWindow2() {
        View view = LayoutInflater.from(this).inflate(R.layout.listview_for_tj_dropdown, new LinearLayout(this), false);
        ListView lv = (ListView) view.findViewById(R.id.listview);
        final TJDropdownAdapter adapter = new TJDropdownAdapter(this, SORT_INFO_ARRAY);
        adapter.setSelectedItemIndex(mIndexOrder);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                adapter.setSelectedItemIndex(position);
                adapter.notifyDataSetChanged();
                mIndexOrder = position;
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                //执行过滤
                doPointFilter();
            }
        });

        showViewWithPopWindow(view, 1);
    }

    private void showPopupWindow3() {
        PointFilter pf = new PointFilter(mContext, mPointFilterModel);
        pf.setOnPointFilterListener(new PointFilter.OnPointFilterListener() {
            @Override
            public void onPointFilter() {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                doPointFilter();
            }
        });
        View view = pf.createView(null);
        showViewWithPopWindow(view, 2);
    }

    private int[] mTextIds = new int[]{
            R.id.textview_t_1,
            R.id.textview_t_2,
            R.id.textview_t_3,
    };

    private int[] mImageIds = new int[]{
            R.id.imageview_arrow_1,
            R.id.imageview_arrow_2,
            R.id.imageview_arrow_3,
    };

    private void showViewWithPopWindow(final View view, final int index) {
        mPopWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        });
        final TextView t = (TextView) findViewById(mTextIds[index]);
        if (t != null) {
            t.setTextColor(ContextCompat.getColor(mContext, R.color.tj_theme));
        }

        final ImageView i = (ImageView) findViewById(mImageIds[index]);
        if (i != null) {
            i.setImageResource(R.drawable.ico_arrow_sm_green_u);
        }

        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(new PaintDrawable(Color.argb(99, 99, 99, 99)));
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (t != null && i != null) {
                    t.setTextColor(Color.rgb(66, 66, 66));
                    i.setImageResource(R.drawable.ico_arrow_sm_grey_d);
                }
            }
        });
        //在android7.0下，会有显示问题，这里改用showAtLocation显示
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mPopWindow.showAsDropDown(mViewPopParent, 0, 0);
        } else {
            int[] location = new int[2];
            mViewPopParent.getLocationOnScreen(location);
            int y = location[1];
            Log.d(TAG, "y:" + y + ",h:" + mViewPopParent.getHeight());
            mPopWindow.showAtLocation(mViewPopParent, Gravity.NO_GRAVITY, 0, y + mViewPopParent.getHeight());
        }
    }


    private void doPointFilter() {
        SelectPointsTask task = new SelectPointsTask();
        task.execute();
    }

    private class SelectPointsTask extends AsyncTask<Void, Void, Integer> {

        private List<JsonPointsOverview> mDataNew;

        @Override
        protected Integer doInBackground(Void... params) {
            //根据第一栏筛选
            mDataNew = new ArrayList<JsonPointsOverview>();
            if (mIndexArea == 0) {
                //还要根据第三栏再筛选一次
                for (JsonPointsOverview item : mData) {
                    if (PointFilter.isPointFiltered(item, mPointFilterModel)) {
                        continue;
                    }
                    mDataNew.add(item);
                }
            } else {
                for (JsonPointsOverview jsonPointsOverview : mData) {
                    if (PointFilter.isPointFiltered(jsonPointsOverview, mPointFilterModel)) {
                        continue;
                    }
                    float distance = MapUtil.calculateDistanceEx(jsonPointsOverview.lat, jsonPointsOverview.lng);
                    jsonPointsOverview.distance = distance;
                    if (distance <= AREA_VALUE_ARRAY[mIndexArea]) {
                        mDataNew.add(jsonPointsOverview);
                    }
                }
            }

            int sortByDistance = 0, sortByFree = 1, sortByEvaluate = 2;
            //后排序
            if (mIndexOrder == sortByDistance) {
                Collections.sort(mDataNew, new DistanceComparator());
            } else if (mIndexOrder == sortByFree) {
                Collections.sort(mDataNew, new IdleComparator());
            } else if (mIndexOrder == sortByEvaluate) {
                Collections.sort(mDataNew, new MarkComparator());
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (mDialog != null) {
                mDialog.dismiss();
            }
            if (result == 0 && mDataNew != null) {
                mAdapter = new PointListAdapter(mContext, mDataNew);
                mListView.setAdapter(mAdapter);//为ListView组件添加适配器
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mDialog != null && !mDialog.isShowing()) {
                mDialog = ProgressDialog.show(mContext, null, "正在处理...", true, false);
            }
        }

    }

    private static class DistanceComparator implements Comparator<JsonPointsOverview> {
        @Override
        public int compare(JsonPointsOverview lhs, JsonPointsOverview rhs) {
            //按距离 由近到远 排列
            return Double.valueOf(lhs.distance).compareTo(Double.valueOf(rhs.distance));
        }
    }

    private static class IdleComparator implements Comparator<JsonPointsOverview> {
        @Override
        public int compare(JsonPointsOverview lhs, JsonPointsOverview rhs) {
            //按空闲桩数 由多到少 排列
            if (lhs.idleNum == rhs.idleNum) {
                return 0;
            } else if (lhs.idleNum > rhs.idleNum) {
                return -1;
            } else {
                return 1;
            }
        }
    }

    private static class MarkComparator implements Comparator<JsonPointsOverview> {
        @Override
        public int compare(JsonPointsOverview lhs, JsonPointsOverview rhs) {
            //按评分 由多到少 排列
            double l = 0;
            double r = 0;
            try {
                if (lhs.mark != null) {
                    l = Double.parseDouble(lhs.mark);
                }
                if (rhs.mark != null) {
                    r = Double.parseDouble(rhs.mark);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            if (l == r) {
                return 0;
            } else if (l > r) {
                return -1;
            } else {
                return 1;
            }
        }
    }

}